<script setup>
  import { ref, reactive } from 'vue'
  import { ElMessage } from 'element-plus'
  import { UserFilled, Edit, Lock, Clock } from '@element-plus/icons-vue'
  import { useAdminStore } from '@/store/admin'
  import { adminModifyService1 } from '@/api/admin'
import { useRoute } from 'vue-router'

  const route = useRoute()
  const adminStore = useAdminStore()

  // 用户信息
//   const adminInfo = reactive({
//     userId: 'ADMIN_2025',
//     userName: '系统管理员',
//     role: 0,
//     account: 'admin@acm.com',
//     avatar: ''
//   })

  const adminInfo = ref({...adminStore.getAdmin()})
  
  // 角色映射
  const roleMap = {
    1: '超级管理员',
    2: '老师',
    3: '现役队长',
    4: '退役队长'
  }
  
  // 密码修改表单
  const pwdFormRef = ref(null)
  const pwdForm = reactive({
    newPassword: '',
    confirmPassword: ''
  })
  
  // 密码验证规则
  const pwdRules = {
    newPassword: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, message: '密码长度至少6位', trigger: 'blur' }
    ],
    confirmPassword: [
      { validator: (rule, value, callback) => {
        if (value !== pwdForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
    ]
  }
  
  // 登录日志模拟数据
  const loginLogs = ref([
    { time: '2025-03-28 09:30', ip: '192.168.1.100', location: '上海' },
    { time: '2025-03-27 15:20', ip: '10.0.0.1', location: '北京' }
  ])
  
  // 交互状态
  const activeCollapse = ref(['detail'])
  const showSuccess = ref(false)
  
  // 头像上传处理
  const handleAvatarUpload = (file) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      adminInfo.value.avatar = e.target.result
      ElMessage.success('头像更新成功')
    }
    reader.readAsDataURL(file)
    return false
  }
  
  // 修改昵称
  const handleUpdateName = async() => {
    if (!adminInfo.value.userName.trim()) {
      ElMessage.error('昵称不能为空')
      return
    }
    const res = await adminModifyService1(adminInfo.value)
    if(res.data.status === 'success'){
        //修改全局信息
        adminStore.setAdmin(adminInfo.value)
        showSuccess.value = true
        setTimeout(() => {
            showSuccess.value = false
            window.location.reload()
        }, 1000)
    }else{
        ElMessage.error(res.data.info)
    }
    
  }
  
  // 修改密码
  const handleUpdatePassword = () => {
    pwdFormRef.value.validate(async valid => {
      if (valid) {
        // API调用
        adminInfo.value.password = pwdForm.newPassword
        const res = await adminModifyService1(adminInfo.value)
        if(res.data.status === 'success'){
            setTimeout(() => {
                ElMessage.success('密码已更新')
                pwdFormRef.value.resetFields()
            }, 500)
        }else{
            ElMessage.error(res.data.info)
        }
      }
    })
  }
</script>

<template>
    <div class="admin-profile">
      <!-- 个人信息概览 -->
      <el-card class="profile-card">
        <template #header>
          <div class="card-header">
            <h2>管理员个人中心</h2>
            <el-tag type="success">{{ roleMap[adminInfo.role] }}</el-tag>
          </div>
        </template>
  
        <!-- 头像与基本信息 -->
        <div class="profile-base">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="handleAvatarUpload"
          >
            <img v-if="adminInfo.avatar" :src="adminInfo.avatar" class="avatar"/>
            <!-- <el-icon v-else class="avatar-uploader-icon"><UserFilled /></el-icon> -->
          </el-upload>
          <div class="base-info">
            <h3>{{ adminInfo.userName }}</h3>
            <!-- <p>账号：{{ adminInfo.account }}</p> -->
            <p>用户ID：{{ adminInfo.userId }}</p>
          </div>
        </div>
  
        <!-- 详细信息折叠面板 -->
        <el-collapse v-model="activeCollapse">
          <el-collapse-item title="详细信息" name="detail">
            <el-descriptions :column="2" border>
              <!-- <el-descriptions-item label="注册时间">2025-03-20</el-descriptions-item> -->
              <!-- <el-descriptions-item label="最后登录IP(未开放)">192.168.1.101</el-descriptions-item> -->
              <!-- <el-descriptions-item label="管辖竞赛数">15场</el-descriptions-item> -->
              <el-descriptions-item label="系统权限">{{ roleMap[adminInfo.role] }}</el-descriptions-item>
            </el-descriptions>
          </el-collapse-item>
        </el-collapse>
      </el-card>
  
      <!-- 功能操作区 -->
      <div class="action-grid">
        <!-- 修改昵称 -->
        <el-card class="action-card">
          <template #header>
            <div class="card-header">
              <el-icon><Edit /></el-icon>
              <span>身份信息设置</span>
            </div>
          </template>
          <el-form label-width="100px">
            <el-form-item label="管理员昵称">
              <el-input v-model="adminInfo.userName" />
              <el-button 
                type="primary" 
                @click="handleUpdateName"
                class="confirm-btn"
              >
                确认修改
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
  
        <!-- 修改密码 -->
        <el-card class="action-card">
          <template #header>
            <div class="card-header">
              <el-icon><Lock /></el-icon>
              <span>安全设置</span>
            </div>
          </template>
          <el-form 
            :model="pwdForm" 
            :rules="pwdRules" 
            ref="pwdFormRef"
            label-width="80px"
          >
            <el-form-item label="新密码" prop="newPassword">
              <el-input type="password" v-model="pwdForm.newPassword" />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input type="password" v-model="pwdForm.confirmPassword" />
            </el-form-item>
            <el-button 
              type="danger" 
              @click="handleUpdatePassword"
              class="confirm-btn"
            >
              重置密码
            </el-button>
          </el-form>
        </el-card>
  
        <!-- 登录日志 -->
        <!-- <el-card class="action-card">
          <template #header>
            <div class="card-header">
              <el-icon><Clock /></el-icon>
              <span>登录记录</span>
            </div>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="(log, index) in loginLogs"
              :key="index"
              :timestamp="log.time"
            >
              {{ log.ip }}（{{ log.location }}）
            </el-timeline-item>
          </el-timeline>
        </el-card> -->
      </div>
  
      <!-- 操作反馈 -->
      <transition name="el-zoom-in-top">
        <el-alert 
          v-if="showSuccess" 
          title="信息更新成功" 
          type="success" 
          class="notification"
          @close="showSuccess = false"
        />
      </transition>
    </div>
</template>
  
  <style scoped>
  .admin-profile {
    max-width: 1200px;
    margin: 20px auto;
    padding: 20px;
  }
  
  .profile-card {
    margin-bottom: 24px;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0,0,0,0.1);
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 16px;
  }
  
  .profile-base {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
  }
  
  .avatar-uploader {
    width: 120px;
    height: 120px;
    border: 2px dashed var(--el-border-color);
    border-radius: 50%;
    cursor: pointer;
    transition: border-color 0.3s;
  }
  
  .avatar-uploader:hover {
    border-color: var(--el-color-primary);
  }
  
  .avatar {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    object-fit: cover;
  }
  
  .base-info {
    margin-left: 30px;
  }
  
  .action-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(380px, 1fr));
    gap: 24px;
  }
  
  .action-card {
    border-radius: 8px;
    transition: transform 0.3s;
  }
  
  .action-card:hover {
    transform: translateY(-5px);
  }
  
  .confirm-btn {
    margin-top: 15px;
    width: 100%;
  }
  
  .notification {
    position: fixed;
    top: 24px;
    right: 24px;
    width: 380px;
    z-index: 2000;
  }
  
  .el-timeline {
    padding-left: 10px;
  }
  </style>